<script setup>
import { ref, onMounted } from 'vue'
import { ElMessage } from 'element-plus'
import { getRechargeList, approveRecharge } from '@/api/user'
import { ElMessageBox } from 'element-plus'

const rechargeList = ref([])

const fetchList = async () => {
  const res = await getRechargeList()
  rechargeList.value = res.data
}

const handleApprove = async (id, approved) => {
  try {
    const res = await approveRecharge({ requestId: id, approved })
    if (res.status) {
      ElMessage.success(approved ? '已同意充值' : '已拒绝充值')
      fetchList()
    } else {
      ElMessage.error(res.message || '操作失败')
    }
  } catch (error) {
    ElMessage.error('请求失败：' + error.message)
  }
}


const clearMessages = () => {
  ElMessageBox.confirm('此操作将清除所有已处理的消息，是否继续？', '提示', {
    confirmButtonText: '确定',
    cancelButtonText: '取消',
    type: 'warning',
  }).then(() => {
    // 保留 status === 0 的项（待处理）
    rechargeList.value = rechargeList.value.filter(item => item.status === 0)
    ElMessage.success('已清除已处理消息')
  }).catch(() => {
    ElMessage.info('已取消操作')
  })
}



onMounted(fetchList)
</script>

<template>
  <div class="message-list">
    <!-- 清除按钮 -->
    <div style="margin-bottom: 10px; text-align: right;">
      <el-button type="danger" @click="clearMessages">清除已处理消息</el-button>
    </div>
    <el-table :data="rechargeList" border>
      <el-table-column prop="userId" label="用户ID" />
      <el-table-column prop="amount" label="充值金额" />
      <el-table-column prop="status" label="状态">
        <template #default="{ row }">
          <el-tag type="warning" v-if="row.status === 0">待处理</el-tag>
          <el-tag type="success" v-else-if="row.status === 1">已同意</el-tag>
          <el-tag type="danger" v-else>已拒绝</el-tag>
        </template>
      </el-table-column>
      <el-table-column label="操作">
        <template #default="{ row }">
          <el-button v-if="row.status === 0" size="small" type="primary" @click="handleApprove(row.id, true)">同意</el-button>
          <el-button v-if="row.status === 0" size="small" type="danger" @click="handleApprove(row.id, false)">拒绝</el-button>
        </template>
      </el-table-column>
    </el-table>
  </div>
</template>

<style scoped>
.message-list {
  padding: 20px;
}
</style>
